<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="view," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="实现一个自定义列表的Android程序。">
<meta property="og:type" content="article">
<meta property="og:title" content="自定义ListView">
<meta property="og:url" content="http://yoursite.com/2017/02/28/201702/自定义ListView/index.html">
<meta property="og:site_name" content="HoneyGuide's Blog">
<meta property="og:description" content="实现一个自定义列表的Android程序。">
<meta property="og:image" content="http://yoursite.com/img/201702/listview.png">
<meta property="og:updated_time" content="2017-02-28T14:05:05.065Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="自定义ListView">
<meta name="twitter:description" content="实现一个自定义列表的Android程序。">
<meta name="twitter:image" content="http://yoursite.com/img/201702/listview.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'R1W2VDDO1V',
      apiKey: '773854c4c250e5a5cf9cddd97ebcc167',
      indexName: 'Hexo_search',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/02/28/201702/自定义ListView/"/>





  <title> 自定义ListView | HoneyGuide's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">﻿<div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">HoneyGuide's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay hungry & Stay young</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">

　　　　　　<!--增加的代码 start-->

          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/02/28/201702/自定义ListView/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="HoneyGuide">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HoneyGuide's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                自定义ListView
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-02-28T00:00:00+08:00">
                2017-02-28
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>实现一个自定义列表的Android程序。<br><a id="more"></a><br>程序将实现一个使用自定义的适配器（Adapter）绑定数据，通过contextView.setTag绑定数据有按钮的ListView。 </p>
<p>系统显示列表（ListView）时，首先会实例化一个适配器，本文将实例化一个自定义的适配器。</p>
<p>实现 自定义适配器，必须手动映射数据，这时就需要重写getView()方法，系统在绘制列表的每一行的时候 将调用此方法。 </p>
<p>ListView在开始绘制的时候，系统自动调用getCount()函数，根据函数返回值得到ListView的长度， 然后根据这个长度，调用getView()逐一画出每一行。 </p>
<h3 id="步骤"><a href="#步骤" class="headerlink" title="步骤"></a>步骤</h3><h4 id="新建一个list-XML"><a href="#新建一个list-XML" class="headerlink" title="新建一个list.XML"></a>新建一个list.XML</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;  </div><div class="line">&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;  </div><div class="line">    android:layout_width=&quot;match_parent&quot;  </div><div class="line">    android:layout_height=&quot;match_parent&quot;  </div><div class="line">    android:orientation=&quot;vertical&quot; &gt;  </div><div class="line">    &lt;LinearLayout android:layout_width=&quot;match_parent&quot;  </div><div class="line">        android:layout_height=&quot;match_parent&quot;  </div><div class="line">        android:orientation=&quot;horizontal&quot; android:background=&quot;#f1e4f1&quot;&gt;  </div><div class="line">        &lt;ImageView   </div><div class="line">            android:id=&quot;@+id/image&quot;  </div><div class="line">            android:layout_width=&quot;wrap_content&quot;  </div><div class="line">            android:layout_height=&quot;wrap_content&quot;/&gt;  </div><div class="line">        &lt;TextView   </div><div class="line">            android:id=&quot;@+id/title&quot;  </div><div class="line">            android:layout_width=&quot;wrap_content&quot;  </div><div class="line">            android:layout_height=&quot;wrap_content&quot;  </div><div class="line">            android:textColor=&quot;#666872&quot;/&gt;  </div><div class="line">        &lt;Button   </div><div class="line">            android:id=&quot;@+id/view&quot;  </div><div class="line">            android:layout_width=&quot;wrap_content&quot;  </div><div class="line">            android:layout_height=&quot;wrap_content&quot;  </div><div class="line">            android:text=&quot;详细&quot;/&gt;  </div><div class="line">    &lt;/LinearLayout&gt;  </div><div class="line">    &lt;TextView   </div><div class="line">        android:id=&quot;@+id/info&quot;  </div><div class="line">        android:layout_width=&quot;wrap_content&quot;  </div><div class="line">        android:layout_height=&quot;wrap_content&quot;  </div><div class="line">        android:textColor=&quot;#666872&quot;/&gt;  </div><div class="line">&lt;/LinearLayout&gt;</div></pre></td></tr></table></figure>
<h4 id="新建一个适配器类MyAdspter-java"><a href="#新建一个适配器类MyAdspter-java" class="headerlink" title="新建一个适配器类MyAdspter.java"></a>新建一个适配器类MyAdspter.java</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div></pre></td><td class="code"><pre><div class="line">public class MyAdspter extends BaseAdapter &#123;  </div><div class="line">  </div><div class="line">    private List&lt;Map&lt;String, Object&gt;&gt; data;  </div><div class="line">    private LayoutInflater layoutInflater;  </div><div class="line">    private Context context;  </div><div class="line">    public MyAdspter(Context context,List&lt;Map&lt;String, Object&gt;&gt; data)&#123;  </div><div class="line">        this.context=context;  </div><div class="line">        this.data=data;  </div><div class="line">        this.layoutInflater=LayoutInflater.from(context);  </div><div class="line">    &#125;  </div><div class="line">    /** </div><div class="line">     * 组件集合，对应list.xml中的控件 </div><div class="line">     * @author Administrator </div><div class="line">     */  </div><div class="line">    public final class Zujian&#123;  </div><div class="line">        public ImageView image;  </div><div class="line">        public TextView title;  </div><div class="line">        public Button view;  </div><div class="line">        public TextView info;  </div><div class="line">    &#125;  </div><div class="line">    @Override  </div><div class="line">    public int getCount() &#123;  </div><div class="line">        return data.size();  </div><div class="line">    &#125;  </div><div class="line">    /** </div><div class="line">     * 获得某一位置的数据 </div><div class="line">     */  </div><div class="line">    @Override  </div><div class="line">    public Object getItem(int position) &#123;  </div><div class="line">        return data.get(position);  </div><div class="line">    &#125;  </div><div class="line">    /** </div><div class="line">     * 获得唯一标识 </div><div class="line">     */  </div><div class="line">    @Override  </div><div class="line">    public long getItemId(int position) &#123;  </div><div class="line">        return position;  </div><div class="line">    &#125;  </div><div class="line">  </div><div class="line">    @Override  </div><div class="line">    public View getView(int position, View convertView, ViewGroup parent) &#123;  </div><div class="line">        Zujian zujian=null;  </div><div class="line">        if(convertView==null)&#123;  </div><div class="line">            zujian=new Zujian();  </div><div class="line">            //获得组件，实例化组件  </div><div class="line">            convertView=layoutInflater.inflate(R.layout.list, null);  </div><div class="line">            zujian.image=(ImageView)convertView.findViewById(R.id.image);  </div><div class="line">            zujian.title=(TextView)convertView.findViewById(R.id.title);  </div><div class="line">            zujian.view=(Button)convertView.findViewById(R.id.view);  </div><div class="line">            zujian.info=(TextView)convertView.findViewById(R.id.info);  </div><div class="line">            convertView.setTag(zujian);  </div><div class="line">        &#125;else&#123;  </div><div class="line">            zujian=(Zujian)convertView.getTag();  </div><div class="line">        &#125;  </div><div class="line">        //绑定数据  </div><div class="line">        zujian.image.setBackgroundResource((Integer)data.get(position).get(&quot;image&quot;));  </div><div class="line">        zujian.title.setText((String)data.get(position).get(&quot;title&quot;));  </div><div class="line">        zujian.info.setText((String)data.get(position).get(&quot;info&quot;));  </div><div class="line">        return convertView;  </div><div class="line">    &#125;  </div><div class="line">  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>实际开发种LayoutInflater这个类还是非常有用的。它的作用类似于findViewById()，不同点是LayoutInflater是用来找layout下xml布局文件，并且会实例化。 </p>
<p>getView()的三个参数：position表示将显示的是第几行，covertView是从布局文件中inflate来的布 局。我们用LayoutInflater的方法将定义好的list.xml文件提取成View实例用来显示。然后将xml文件中的各个组件实例化，这样便可以将数据对应到各个组件上了。但是按钮为了响应点击事件，需要为它添加点击监听器，这样就能捕获点击事件。 </p>
<h4 id="activity-main-xml中添加ListView控件"><a href="#activity-main-xml中添加ListView控件" class="headerlink" title="activity_main.xml中添加ListView控件"></a>activity_main.xml中添加ListView控件</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;  </div><div class="line">    xmlns:tools=&quot;http://schemas.android.com/tools&quot;  </div><div class="line">    android:layout_width=&quot;match_parent&quot;  </div><div class="line">    android:layout_height=&quot;match_parent&quot;  </div><div class="line">    android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;  </div><div class="line">    android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;  </div><div class="line">    android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;  </div><div class="line">    android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;  </div><div class="line">    tools:context=&quot;.MainActivity&quot; &gt;  </div><div class="line">    &lt;ListView   </div><div class="line">        android:id=&quot;@+id/list&quot;  </div><div class="line">        android:layout_width=&quot;fill_parent&quot;  </div><div class="line">        android:layout_height=&quot;fill_parent&quot;&gt;&lt;/ListView&gt;  </div><div class="line">&lt;/RelativeLayout&gt;</div></pre></td></tr></table></figure>
<h4 id="在activity中调用ListView"><a href="#在activity中调用ListView" class="headerlink" title="在activity中调用ListView"></a>在activity中调用ListView</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line">1.	public class MainActivity extends Activity &#123;  </div><div class="line">2.	  </div><div class="line">3.	    private ListView listView=null;   </div><div class="line">4.	    @Override  </div><div class="line">5.	    protected void onCreate(Bundle savedInstanceState) &#123;  </div><div class="line">6.	        super.onCreate(savedInstanceState);  </div><div class="line">7.	        setContentView(R.layout.activity_main);  </div><div class="line">8.	        listView=(ListView)findViewById(R.id.list);  </div><div class="line">9.	        List&lt;Map&lt;String, Object&gt;&gt; list=getData();  </div><div class="line">10.	        listView.setAdapter(new MyAdspter(this, list));  </div><div class="line">11.	    &#125;  </div><div class="line">12.	    @Override  </div><div class="line">13.	    public boolean onCreateOptionsMenu(Menu menu) &#123;  </div><div class="line">14.	        getMenuInflater().inflate(R.menu.main, menu);  </div><div class="line">15.	        return true;  </div><div class="line">16.	    &#125;  </div><div class="line">17.	  </div><div class="line">18.	    public List&lt;Map&lt;String, Object&gt;&gt; getData()&#123;  </div><div class="line">19.	        List&lt;Map&lt;String, Object&gt;&gt; list=new ArrayList&lt;Map&lt;String,Object&gt;&gt;();  </div><div class="line">20.	        for (int i = 0; i &lt; 10; i++) &#123;  </div><div class="line">21.	            Map&lt;String, Object&gt; map=new HashMap&lt;String, Object&gt;();  </div><div class="line">22.	            map.put(&quot;image&quot;, R.drawable.ic_launcher);  </div><div class="line">23.	            map.put(&quot;title&quot;, &quot;这是一个标题&quot;+i);  </div><div class="line">24.	            map.put(&quot;info&quot;, &quot;这是一个详细信息&quot;+i);  </div><div class="line">25.	            list.add(map);  </div><div class="line">26.	        &#125;  </div><div class="line">27.	        return list;  </div><div class="line">28.	    &#125;  </div><div class="line">29.	&#125;</div></pre></td></tr></table></figure>
<p><img src="/img/201702/listview.png" alt="image"></p>
<h3 id="性能优化"><a href="#性能优化" class="headerlink" title="性能优化"></a>性能优化</h3><p>ListView优化主要有下面几个方面：</p>
<h4 id="convertView重用"><a href="#convertView重用" class="headerlink" title="convertView重用"></a>convertView重用</h4><p>首先讲下ListView的原理：ListView中的每一个Item显示都需要Adapter调用一次getView()的方法，这个方法会传入一个convertView的参数，这个方法返回的View就是这个Item显示的View。如果当Item的数量足够大，再为每一个Item都创建一个View对象，必将占用很多内存空间，即创建View对象（mInflater.inflate(R.layout.lv_item, null)；；从xml中生成View，这是属于IO操作）是耗时操作，所以必将影响性能。Android提供了一个叫做Recycler(反复循环)的构件，就是当ListView的Item从滚出屏幕视角之外，对应Item的View会被缓存到Recycler中，相应的会从生成一个Item，而此时调用的getView中的convertView参数就是滚出屏幕的缓存Item的View，所以说如果能重用这个convertView，就会大大改善性能。<br>当这个convertView不存在时，即第一次使用它，我们就创建一个item布局的View对象并赋给convertView，以后使用convertView时，只需从convertView中getTag取出来就可以，不需要再次创建item的布局对象了，这样便提高了性能。</p>
<h4 id="ViewHolder的子View复用"><a href="#ViewHolder的子View复用" class="headerlink" title="ViewHolder的子View复用"></a>ViewHolder的子View复用</h4><p>我们都知道在getView()方法中的操作是这样的：先从xml中创建view对象（inflate操作，我们采用了重用convertView方法优化），然后在这个view去findViewById，找到每一个item的子View的控件对象，如：ImageView、TextView等。这里的findViewById操作是一个树查找过程，也是一个耗时的操作，所以这里也需要优化，就是使用ViewHolder，把每一个item的子View控件对象都放在Holder中，当第一次创建convertView对象时，便把这些item的子View控件对象findViewById实例化出来并保存到ViewHolder对象中。然后用convertView的setTag将viewHolder对象设置到Tag中， 当以后加载ListView的item时便可以直接从Tag中取出复用ViewHolder对象中的，不需要再findViewById找item的子控件对象了。这样便大大提高了性能。</p>
<p>我们一般考虑使用ViewHolder方式来实现BaseAdapter。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line">//在外面先定义，ViewHolder静态类</div><div class="line">static class ViewHolder</div><div class="line">&#123;</div><div class="line">	public ImageView img;</div><div class="line">	public TextView title;</div><div class="line">	public TextView info;</div><div class="line">&#125;</div><div class="line">//然后重写getView</div><div class="line">@Override</div><div class="line">public View getView(int position, View convertView, ViewGroup parent) &#123;</div><div class="line">	ViewHolder holder;</div><div class="line">	if(convertView == null)</div><div class="line">	&#123;</div><div class="line">		holder = new ViewHolder();</div><div class="line">		convertView = mInflater.inflate(R.layout.list_item, null);</div><div class="line">		holder.img = (ImageView)item.findViewById(R.id.img)</div><div class="line">		holder.title = (TextView)item.findViewById(R.id.title);</div><div class="line">		holder.info = (TextView)item.findViewById(R.id.info);</div><div class="line">		convertView.setTag(holder);</div><div class="line">	&#125;else</div><div class="line">	&#123;</div><div class="line">		holder = (ViewHolder)convertView.getTag();</div><div class="line">	&#125;</div><div class="line">		holder.img.setImageResource(R.drawable.ic_launcher);</div><div class="line">		holder.title.setText(&quot;Hello&quot;);</div><div class="line">		holder.info.setText(&quot;World&quot;);</div><div class="line">	&#125;</div><div class="line">	return convertView;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>ViewHolder 在 convertView 第一次inflate的时候绑定了相关的子元素，并被 convertView 保存下来（setTag方法），当相同的 convertView再次需要显示的时候直接调用 convertView 的getTag取出ViewHolder，并对ViewHolder中的元素赋值。使用ViewHolder模式避免了没有必要的调用findViewById()：因为太多的findViewById也会影响性能 ，这点不容易考虑到。</p>
<h4 id="HolderView方式"><a href="#HolderView方式" class="headerlink" title="HolderView方式"></a>HolderView方式</h4><p>在HolderView方式中，目的同样是为了避免反复的调用findViewById，但是我们将这个findViewByIdde 任务交给了一个HolderView对象。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div></pre></td><td class="code"><pre><div class="line">@Override</div><div class="line">public View getView(int i, View convertView, ViewGroup viewGroup) &#123;</div><div class="line">	HolderView holderView;</div><div class="line">	// Important to not just null check, but rather to a instanceof</div><div class="line">	// since we might get any subclass of view here.</div><div class="line">	if (convertView instanceof HolderView) &#123;</div><div class="line">		holderView = (HolderView) convertView;</div><div class="line">	&#125; else &#123;</div><div class="line">		holderView = new HolderView(mContext);</div><div class="line">	&#125;</div><div class="line">	holderView.bind(&quot;标题&quot;, R.drawable.ic_launcher, &quot;sajsa&quot;);</div><div class="line">	return holderView;</div><div class="line">&#125;</div><div class="line">public class HolderView extends GridLayout &#123;</div><div class="line">	private ImageView img;</div><div class="line">	private TextView title;</div><div class="line">	private TextView info;</div><div class="line">	public HolderView(Context context, AttributeSet attrs) &#123;</div><div class="line">		super(context, attrs);</div><div class="line">		View v = LayoutInflater.from(context).inflate(R.layout.list_item, this);</div><div class="line">		title = (TextView) v.findViewById(R.id.title);</div><div class="line">		img = (ImageView)item.findViewById(R.id.img)</div><div class="line">		info = (TextView)item.findViewById(R.id.info);</div><div class="line">	&#125;</div><div class="line">	public void bind(String stringtitle,int imgrsc, String stringinfo) &#123;</div><div class="line">		title.setText(stringtitle);</div><div class="line">		img.setImageResource(imgrsc);</div><div class="line">		info.setText(stringinfo);</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>HolderView自己维护一个子元素的集合，同时对外提供绑定数据的公共方法bind。HolderView方式的思想是：对于ListView来讲，每一个Item本身是同一个类只是数据不同。 但是需要注意的是使用HolderView方式在Adapter中getView返回的是HolderView对象。</p>
<p><em>ViewHolder方式使用简单，HolderView方式更符合面向对象规范。</em></p>
<h3 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h3><p><a href="http://daoshud1.iteye.com/blog/1874241" target="_blank" rel="external">http://daoshud1.iteye.com/blog/1874241</a><br><a href="http://www.tuicool.com/articles/jyMNVvE" target="_blank" rel="external">http://www.tuicool.com/articles/jyMNVvE</a><br><a href="http://www.2cto.com/kf/201505/398415.html" target="_blank" rel="external">http://www.2cto.com/kf/201505/398415.html</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/view/" rel="tag"># view</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/02/27/201702/Android绘图/" rel="next" title="Android绘图">
                <i class="fa fa-chevron-left"></i> Android绘图
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/02/28/201702/动态加载view组件/" rel="prev" title="动态加载view组件">
                动态加载view组件 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="HoneyGuide" />
          <p class="site-author-name" itemprop="name">HoneyGuide</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              
                <span class="site-state-item-count">34</span>
                <span class="site-state-item-name">标签</span>
              
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#步骤"><span class="nav-number">1.</span> <span class="nav-text">步骤</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#新建一个list-XML"><span class="nav-number">1.1.</span> <span class="nav-text">新建一个list.XML</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#新建一个适配器类MyAdspter-java"><span class="nav-number">1.2.</span> <span class="nav-text">新建一个适配器类MyAdspter.java</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#activity-main-xml中添加ListView控件"><span class="nav-number">1.3.</span> <span class="nav-text">activity_main.xml中添加ListView控件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在activity中调用ListView"><span class="nav-number">1.4.</span> <span class="nav-text">在activity中调用ListView</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#性能优化"><span class="nav-number">2.</span> <span class="nav-text">性能优化</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#convertView重用"><span class="nav-number">2.1.</span> <span class="nav-text">convertView重用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ViewHolder的子View复用"><span class="nav-number">2.2.</span> <span class="nav-text">ViewHolder的子View复用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#HolderView方式"><span class="nav-number">2.3.</span> <span class="nav-text">HolderView方式</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参考"><span class="nav-number">3.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HoneyGuide</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  



  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="local-search-pop-overlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


  

</body>
</html>
